package com.yj.suncity.activity;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.yj.suncity.Application;
import com.yj.suncity.R;
import com.yj.suncity.activity.shouye.CityHelpListActivity;
import com.yj.suncity.activity.shouye.DigouShopListActivity;
import com.yj.suncity.activity.shouye.DuihuanShopListActivity;
import com.yj.suncity.activity.shouye.HuodongDetailActivity;
import com.yj.suncity.activity.shouye.InvitationActivity;
import com.yj.suncity.activity.shouye.MyYinkuActivity;
import com.yj.suncity.activity.shouye.OfferListActivity;
import com.yj.suncity.activity.shouye.ProductDateilsActivity;
import com.yj.suncity.activity.shouye.RecentHuodongActivity;
import com.yj.suncity.activity.shouye.SeeAdvDetailActivity;
import com.yj.suncity.activity.shouye.SeeAdvListActivity;
import com.yj.suncity.activity.shouye.ShopGoodsListActivity;
import com.yj.suncity.activity.shouye.SigninActivity;
import com.yj.suncity.activity.shouye.bean.ShouyeListBean;
import com.yj.suncity.adapter.ShouyeActivityGalleryAdapter;
import com.yj.suncity.adapter.ShouyeGoodsGalleryAdapter;
import com.yj.suncity.adapter.ShouyeGoodsGalleryAdapter.CallBackId;
import com.yj.suncity.adapter.ShouyeShopsGalleryAdapter;
import com.yj.suncity.area.ProvinceSelectActivity;
import com.yj.suncity.async.AsyncTaskUtil;
import com.yj.suncity.async.AsyncTaskUtil.ResultCallBack;
import com.yj.suncity.constant.ShareCon;
import com.yj.suncity.constant.URLCon;
import com.yj.suncity.user.LoginActivity;
import com.yj.suncity.user.ShopCateActivity;
import com.yj.suncity.utis.DialogUtils;
import com.yj.suncity.utis.DialogUtils.ReshActivity;
import com.yj.suncity.utis.GalleryFlow;
import com.yj.suncity.utis.PullToRefreshHeadView;
import com.yj.suncity.utis.PullToRefreshHeadView.OnHeaderRefreshListen;
import com.yj.suncity.utis.SharedPreferencesUtil;
import com.yj.suncity.utis.ToastUtil;
import com.yj.suncity.utis.Utils;
import com.yj.suncity.utis.VerticalViewPager;
import com.yj.suncity.viewpager.VerticalViewPagerScroll;
import com.yj.suncity.viewpager.ViewPagerScrollShouye;

public class ShouYeActivity extends Activity implements OnClickListener,OnHeaderRefreshListen {
	protected static final String TAG = "ShouYeActivity";
	private Context context;
	private int mWidth;
	private DisplayImageOptions options;
	private ImageLoader imageLoader = ImageLoader.getInstance();
	private ViewPager pager;
	private LinearLayout lay_view_select, mLinear_lay_city;
	private ProgressBar progressBar;
	private ViewPagerScrollShouye pagerScroll;
	private Application application;
	private LocationClient mLocationClient;
	private String cityLocation;
	private String areaLocation;
	private PullToRefreshHeadView mPullToRefreshView;
	private boolean mRefreshFlag;
	private String cityId;
	private String cityName;
	private TextView mTxt_city;

	private SharedPreferencesUtil preferencesUtil = SharedPreferencesUtil
			.getInstance();

	private GalleryFlow galleryFlow1, galleryFlow2, galleryFlow3, galleryFlow4;
	private ImageView mIma_1_1, mIma_1_2, mIma_1_3, mIma_1_4;
	private ImageView mIma_2_1, mIma_2_2, mIma_2_3, mIma_2_4;
	private LinearLayout mLay_linear_grid;
	private boolean isLogin;
	private String userId;
	private boolean touch;
	private VerticalViewPager mList_placard;
	private VerticalViewPagerScroll verticalViewPagerScroll;
	private int posi = -1;
	Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case 1:
				onResume();
				break;
			default:
				break;
			}
		};
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_shouye);
		context = this;
		options = new DisplayImageOptions.Builder()
				.showStubImage(R.drawable.android_layout_bg)
				.showImageForEmptyUri(R.drawable.android_layout_bg)
				.showImageOnFail(R.drawable.android_layout_bg)
				.cacheInMemory(true).cacheOnDisc(true)
				// .displayer(new RoundedBitmapDisplayer(10))// 设置成圆角图片
				.bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
				.build();
		mWidth = getResources().getDisplayMetrics().widthPixels;

		cityId = preferencesUtil.getString(context, ShareCon.CITYFILE,
				ShareCon.CITYID, "");// 140881 永济市
		cityName = preferencesUtil.getString(context, ShareCon.CITYFILE,
				ShareCon.CITYNAME, "");// 永济市
		findView();
		checkNet();
	}

	private void findView() {
		mLinear_lay_city = (LinearLayout) findViewById(R.id.linear_lay_city);
		mPullToRefreshView = (PullToRefreshHeadView)findViewById(R.id.pull_refresh_head_view);
		mPullToRefreshView.setOnHeaderRefreshListener(this);
		mLinear_lay_city.setOnClickListener(this);
		mTxt_city = (TextView) findViewById(R.id.txt_city);
		mTxt_city.setText(cityName);
		progressBar = (ProgressBar) findViewById(R.id.probar);
		lay_view_select = (LinearLayout) findViewById(R.id.lay_view_select);
		RelativeLayout layout = (RelativeLayout) findViewById(R.id.lay_view_page);
		layout.setLayoutParams(new LinearLayout.LayoutParams(mWidth,
				(int) (mWidth / 3)));
		pager = (ViewPager) findViewById(R.id.view_pager);

		mLay_linear_grid = (LinearLayout) findViewById(R.id.lay_linear_grid);
		mLay_linear_grid.setLayoutParams(new LinearLayout.LayoutParams(mWidth,
				(int) (mWidth / 1.7)));

		mList_placard = (VerticalViewPager) findViewById(R.id.list_placard);
		mList_placard.setLayoutParams(new LinearLayout.LayoutParams(mWidth,
				Utils.dipTopx(context, 30)));

		galleryFlow1 = (GalleryFlow) findViewById(R.id.gallery_1);
		galleryFlow2 = (GalleryFlow) findViewById(R.id.gallery_2);
		galleryFlow3 = (GalleryFlow) findViewById(R.id.gallery_3);
		galleryFlow4 = (GalleryFlow) findViewById(R.id.gallery_4);
		int dip_10 = Utils.dipTopx(context, 10);
		galleryFlow1.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, (mWidth - dip_10) / 3));
		galleryFlow2.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, (mWidth - dip_10) / 3));
		galleryFlow3.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, (mWidth - dip_10) / 3));
		galleryFlow4.setLayoutParams(new LinearLayout.LayoutParams(
				LayoutParams.MATCH_PARENT, (mWidth - dip_10) / 3));

		if (cityId.equals("") || cityName.equals("")) {// 第一个安装启动
			mLinear_lay_city.performClick();
		}

	}

	private void checkNet() {
		if (Utils.checkNetStatus(context)) {
			startLocation();
			initData();
		} else {
			DialogUtils dialogUtils = DialogUtils.getInstance();
			dialogUtils.AlertDialogUtil(context, "网络未连接，设置网络？",
					new ReshActivity() {

						@Override
						public void reshActivity() {
							Intent wifiSettingsIntent = new Intent(
									"android.settings.WIFI_SETTINGS");
							startActivity(wifiSettingsIntent);
							ShouYeActivity.this.finish();
						}
					});
		}

	}

	/**
	 * 首页定位
	 */
	private void startLocation() {
		application = Application.getInstance();
		mLocationClient = application.getLocationClient();
		mLocationClient.registerLocationListener(mLocationListener);

		mLocationClient.start();
		mLocationClient.requestLocation();

	}

	BDLocationListener mLocationListener = new BDLocationListener() {
		@Override
		public void onReceivePoi(BDLocation arg0) {
			// do nothing
		}

		@Override
		public void onReceiveLocation(BDLocation location) {
			if (location == null || TextUtils.isEmpty(location.getCity())) {
				ToastUtil.ShowToast(context, "定位失败！ ");
			} else {
				cityLocation = location.getCity();
				areaLocation = location.getDistrict();
				ToastUtil
						.ShowToast(context, "您当前的位置是:" + location.getAddrStr());
				Log.v(TAG, "  省份    " + location.getProvince());
				Log.v(TAG, "  城市   " + location.getCity());
				Log.v(TAG, "  区域    " + location.getDistrict());
				Log.v(TAG, "  街道    " + location.getStreet());
				Log.v(TAG, "  当前地点    " + location.getAddrStr());
				Log.v(TAG, "  纬度   " + location.getLatitude());
				Log.v(TAG, "  经度    " + location.getLongitude());
				Log.v(TAG, "  当前时间    " + location.getTime());
			}
		}
	};

	private void initData() {
		String path = URLCon.收藏 + "?action=getindexlist&cityid=" + cityId;
		Log.d("", path);
		AsyncTaskUtil asyncTaskUtil = new AsyncTaskUtil(context, null, null,
				false, progressBar, true, "正在加载......", new ResultCallBack() {
					@Override
					public void JSONResult(JSONObject jsonObject) {
						mPullToRefreshView.onHeaderRefreshComplete();
						ShouyeListBean listBean = new ShouyeListBean(jsonObject);
						pagerScroll = new ViewPagerScrollShouye(context,
								imageLoader, options, pager, lay_view_select,
								listBean.getSuperadvBeans(),mRefreshFlag);
						verticalViewPagerScroll = new VerticalViewPagerScroll(
								context, mList_placard, listBean
										.getPlacardBeans());
						Message message=new Message();
						message.what=1;
						handler.sendMessage(message);

						setGalleryClick(listBean);
					}
				});
		asyncTaskUtil.execute(path);
	}

	@Override
	protected void onResume() {
		if (pagerScroll != null) {
			pagerScroll.startTimer();
		}
		isLogin = preferencesUtil.getBoolean(context, ShareCon.USERFILE,
				ShareCon.ISLOGIN, false);
		if (isLogin) {
			userId = preferencesUtil.getString(context, ShareCon.USERFILE,
					ShareCon.USERID, "");
		} else {
			userId = "";
		}

		if (verticalViewPagerScroll != null) {
			verticalViewPagerScroll.startTimer();
		}
		super.onResume();
	}

	@Override
	protected void onPause() {
		if (pagerScroll != null) {
			pagerScroll.stopTimer();
		}
		if (verticalViewPagerScroll != null) {
			verticalViewPagerScroll.stopTimer();
		}
		super.onPause();
	}

	private void setGalleryClick(ShouyeListBean listBean) {

		galleryFlow1.setAdapter(new ShouyeGoodsGalleryAdapter(context, listBean
				.getGoodsTjBeans(), new CallBackId() {
			@Override
			public void callBackId(String id) {
				Intent intent = new Intent(context,
						ProductDateilsActivity.class);
				intent.putExtra("goodid", id);
				intent.putExtra("flag", 2);
				startActivity(intent);
			}
		}));
		galleryFlow2.setAdapter(new ShouyeGoodsGalleryAdapter(context, listBean
				.getGoodsCxBeans(), new CallBackId() {
			@Override
			public void callBackId(String id) {
				Intent intent = new Intent(context,
						ProductDateilsActivity.class);
				intent.putExtra("goodid", id);
				intent.putExtra("flag", 1);
				startActivity(intent);

			}
		}));
		galleryFlow3.setAdapter(new ShouyeActivityGalleryAdapter(context,
				listBean.getActivityBeans(),
				new ShouyeActivityGalleryAdapter.CallBackId() {
					@Override
					public void callBackId(String id) {
						Intent intent = new Intent(context,
								HuodongDetailActivity.class);
						intent.putExtra("huodongid", id);
						startActivity(intent);
					}
				}));
		galleryFlow4.setAdapter(new ShouyeShopsGalleryAdapter(context, listBean
				.getEntBeans(), new ShouyeShopsGalleryAdapter.CallBackId() {
			@Override
			public void callBackId(String aid, String userid) {
				Intent intent = new Intent(context, SeeAdvDetailActivity.class);
				intent.putExtra("adv_userid", userid);
				intent.putExtra("advid", aid);
				intent.putExtra("flag", 1);
				startActivity(intent);

			}
		}));

		galleryFlow1.setSelection(1);
		galleryFlow2.setSelection(1);
		galleryFlow3.setSelection(1);
		galleryFlow4.setSelection(1);
		galleryFlow1.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					touch = true;
				} else {
					touch = false;
				}
				if (posi == 0 && touch) {
					galleryFlow1.setSelection(1);
				}
				return false;
			}
		});
		galleryFlow1.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				Log.d("hahaha", position + "====" + touch);
				posi = position;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		galleryFlow2.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					touch = true;
				} else {
					touch = false;
				}
				if (posi == 0 && touch) {
					galleryFlow2.setSelection(1);
				}
				return false;
			}
		});
		galleryFlow2.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				Log.d("hahaha", position + "====" + touch);
				posi = position;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		galleryFlow3.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					touch = true;
				} else {
					touch = false;
				}
				if (posi == 0 && touch) {
					galleryFlow3.setSelection(1);
				}
				return false;
			}
		});
		galleryFlow3.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				Log.d("hahaha", position + "====" + touch);
				posi = position;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});
		galleryFlow4.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == MotionEvent.ACTION_UP) {
					touch = true;
				} else {
					touch = false;
				}
				if (posi == 0 && touch) {
					galleryFlow4.setSelection(1);
				}
				return false;
			}
		});
		galleryFlow4.setOnItemSelectedListener(new OnItemSelectedListener() {
			@Override
			public void onItemSelected(AdapterView<?> parent, View view,
					int position, long id) {
				Log.d("hahaha", position + "====" + touch);
				posi = position;
			}

			@Override
			public void onNothingSelected(AdapterView<?> parent) {
			}
		});

	}

	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.linear_lay_city:// 选择城市
			startActivityForResult(new Intent(this,
					ProvinceSelectActivity.class), 101);
			break;
		case R.id.lay_linear_signin:// 签到
			if (!isLogin) {
				startActivity(new Intent(this, LoginActivity.class));
				return;
			}
			Intent intent = new Intent(this, SigninActivity.class);
			intent.putExtra("userid", userId);
			startActivity(intent);
			break;
		case R.id.lay_rela_digoushop:// 促销商城
			Intent intdg = new Intent(this, DigouShopListActivity.class);
			intdg.putExtra("flag", 1);
			startActivity(intdg);
			break;
		case R.id.lay_rela_duihuanshop:// 特价商城
			Intent intdh = new Intent(this, DuihuanShopListActivity.class);
			intdh.putExtra("flag", 1);
			startActivity(intdh);
			break;
		case R.id.lay_rela_recent:// 商家活动
			Intent intactivity = new Intent(this, RecentHuodongActivity.class);
			intactivity.putExtra("flag", 1);
			startActivity(intactivity);
			break;
		case R.id.lay_rela_newproduct:// 推荐商家
			Intent intshop = new Intent(this, ShopGoodsListActivity.class);
			intshop.putExtra("titlename", "推荐商家");
			startActivity(intshop);
			break;
		}
	}

	/**
	 * 九宫格View点击
	 * 
	 * @param v
	 */
	public void ImgClick(View v) {
		switch (v.getId()) {
		case R.id.img_1_1:// 看广告
			Intent intadv = new Intent(this, SeeAdvListActivity.class);
			intadv.putExtra("flag", 1);
			startActivity(intadv);
			break;
		case R.id.img_1_2:// 接悬赏
			Intent intoffer = new Intent(this, OfferListActivity.class);
			intoffer.putExtra("flag", 1);
			startActivity(intoffer);
			break;
		case R.id.img_1_3:// 寻找商家 分类信息
			Intent intent = new Intent(this, ShopCateActivity.class);
			intent.putExtra("flag", 1);
			startActivity(intent);
			break;
		case R.id.img_1_4:// 同城帮帮
			Intent inthelp = new Intent(this, CityHelpListActivity.class);
			inthelp.putExtra("flag", 1);
			startActivity(inthelp);
			break;
		case R.id.img_2_1:// 个人店铺
			// Intent intdh = new Intent(this, DigouShopListActivity.class);
			// intdh.putExtra("flag", 1);
			// startActivity(intdh);
			ToastUtil.ShowToast(context, "暂未开放......");
			break;
		case R.id.img_2_2:// 邀请好友
			Intent intyq = new Intent(this, InvitationActivity.class);
			startActivity(intyq);
			break;
		case R.id.img_2_3:// 生活服务
			// Intent intbmfw = new Intent(this, SeeAdvListActivity.class);
			// intbmfw.putExtra("flag", 1);
			// startActivity(intbmfw);
			ToastUtil.ShowToast(context, "暂未开放......");
			break;
		case R.id.img_2_4:// 我的银库
			startActivity(new Intent(this, MyYinkuActivity.class));
			break;
		}
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (requestCode == 101 && resultCode == 101) {
			Log.d("",
					data.getStringExtra("allname") + "======="
							+ data.getStringExtra("countyname") + "======="
							+ data.getStringExtra("areaid"));
			cityId = data.getStringExtra("areaid");
			cityName = data.getStringExtra("countyname");
			mTxt_city.setText(cityName);

			preferencesUtil.putString(context, ShareCon.CITYFILE,
					ShareCon.CITYID, cityId);
			preferencesUtil.putString(context, ShareCon.CITYFILE,
					ShareCon.CITYNAME, cityName);// 小店区
			initData();

		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	@Override
	public void onHeaderRefresh(PullToRefreshHeadView view) {
		// TODO Auto-generated method stub
		mPullToRefreshView.postDelayed(new Runnable()
	    {
	      public void run()
	      {
	        mRefreshFlag = true;
	        onPause();
	        initData();
	      }
	    }
	    , 1L);
	}

}
